package com.haohan.cloud.scm.api.constant.converter;

import cn.hutool.core.util.StrUtil;
import com.haohan.cloud.scm.api.constant.enums.IBaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author dy
 * @date 2019/8/5
 */
@Component
public class SpringEnumConvertFactory implements ConverterFactory<String, IBaseEnum> {

    @Override
    public <T extends IBaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum<>(targetType);
    }

    private static class StringToEnum<T extends IBaseEnum> implements Converter<String, T> {
        private Class<T> targetType;

        public StringToEnum(Class<T> targetType) {
            this.targetType = targetType;
        }

        @Override
        public T convert(String source) {
            if (StrUtil.isEmpty(source)) {
                return null;
            }
            return (T) SpringEnumConvertFactory.getIEnum(this.targetType, source);
        }
    }

    public static <T extends IBaseEnum> Object getIEnum(Class<T> targetType, String source) {
        T t = null;
        try {
            Method method = targetType.getMethod("getByType", String.class);
            t = (T)method.invoke(null, source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

}
